package com.wl.index.Controller;

import com.wl.entity.PaymentRequest;
import com.wl.entity.PaymentResponse;
import com.wl.entity.PaymentStatusResponse;
import com.wl.index.Biz.Impl.PaymentBizImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/index/payment")
public class PaymentController {
    @Autowired
    private PaymentBizImpl paymentBiz;

    @PostMapping("/create")
    public ResponseEntity<?> createPaymentOrder(@RequestBody PaymentRequest request) {
        try {
            // 创建支付宝订单
            String form = paymentBiz.createOrder(
                    request.getOutTradeNo(),
                    request.getSubject(),
                    request.getTotalAmount(),
                    request.getReturnUrl());

            PaymentResponse response = new PaymentResponse();
            response.setOutTradeNo(request.getOutTradeNo());
            response.setTotalAmount(request.getTotalAmount().toString());
            response.setPayForm(form);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 使用ProblemDetail作为错误响应
            ProblemDetail problemDetail = ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR);
            problemDetail.setTitle("支付订单创建失败");
            problemDetail.setDetail(e.getMessage());
            problemDetail.setProperty("errorCode", "PAYMENT_CREATE_FAILED");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(problemDetail);
        }
    }

    @GetMapping("/status")
    public ResponseEntity<?> checkPaymentStatus(@RequestParam String outTradeNo) {
        try {
            boolean paid = paymentBiz.checkPaymentStatus(outTradeNo);
            PaymentStatusResponse response = new PaymentStatusResponse(outTradeNo, paid);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            ProblemDetail problemDetail = ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR);
            problemDetail.setTitle("支付状态查询失败");
            problemDetail.setDetail(e.getMessage());
            problemDetail.setProperty("errorCode", "PAYMENT_QUERY_FAILED");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(problemDetail);
        }
    }
}
